/**
 * 获取路由信息
 * 统一处理信息格式化
 */
import { useRouter, RouteRecordRaw } from 'vue-router';
import { ComputedRef, computed } from 'vue';
import tools from '@src/utils/tools.js';
const { getUid } = tools;
const user = {
  roles: ['admin', 'user'] // 用户角色
};

// 路由过滤函数
function filterRoutesByRoles(routes: RouteRecordRaw[], userRoles: string[]): RouteRecordRaw[] {
  return routes.filter(route => {
    const routeRoles = route.meta?.roles || [];
    if (routeRoles.includes('*') || !routeRoles.length) {
      return true; // 如果路由对所有角色开放或者没有指定角色，则直接返回 true
    }
    return routeRoles.some(role => userRoles.includes(role));
  });
}

function filterChildRoutes(routes: RouteRecordRaw[]): RouteRecordRaw[] {
  return routes
    .filter(route => route.meta?.show || route.meta?.show === undefined)
    .map(route => ({
      name: route.name || '',
      title: route.meta?.title ?? '未命名',
      id: getUid(),
      path: route.path,
      meta: route.meta,
      children: route.children ? filterChildRoutes(route.children) : []
    }))
    .sort((a, b) => {
      const slotA = a.meta?.slot ?? Infinity;
      const slotB = b.meta?.slot ?? Infinity;
      return slotA - slotB;
    });
}

function getMenu(routes: RouteRecordRaw[]): RouteRecordRaw[] {
  /**
   * 过滤页面
   *   404
   **/
  const filterPaths = ['/:pathMatch(.*)*'];
  const filteredRoutes = routes.filter(route => !filterPaths.includes(route.path));

  const topLevelRoutes = filteredRoutes.flatMap(route => {
    // 检查是否有单个子路由，并且该子路由应该作为一级菜单显示
    if (route.children && route.children.length === 1) {
      const child = route.children[0];
      // 特殊处理 name: 'home' 的路由，不考虑 meta.show
      if (child.name === 'home') {
        return [{
          ...child,
          title: child.meta.title ?? '首页', // 固定标题为"首页"
          id: getUid(),
          meta: {
            ...child.meta,
            show: true, // 确保子路由显示
            slot: -1 // 确保首页总是在最前面
          },
          children: [] // 移除子路由的children属性以避免嵌套
        }];
      } else if (child.meta?.show || child.meta?.show === undefined) {
        return [{
          ...child,
          title: child.meta?.title ?? '未命名',
          id: getUid(),
          meta: child.meta,
          children: []
        }];
      }
    }

    // 对于不是 '/home' 的顶级路由，仍然按照正常逻辑处理
    if (route.meta?.show) {
      return [{
        meta: route.meta,
        title: route.meta?.title ?? '未命名',
        name: route.name ?? '',
        path: route.path,
        id: getUid(),
        children: route.children ? filterChildRoutes(route.children) : []
      }];
    }

    return []; // 不满足条件的路由不加入菜单
  });

  // 最终排序：将 name: 'home' 的路由放在最前面
  return topLevelRoutes.sort((a, b) => {
    const slotA = a.meta?.slot ?? Infinity;
    const slotB = b.meta?.slot ?? Infinity;
    return slotA - slotB;
  });
}

// 构建最终菜单结构
export function useMenu(): ComputedRef<RouteRecordRaw[]> {
  const router = useRouter();
  const allRouterRoutes = router.getRoutes();
  const finalMenu = computed(() => {
    const filteredRoutes = filterRoutesByRoles(allRouterRoutes, user.roles);
    return getMenu(filteredRoutes);
  });
  console.log('最终菜单', finalMenu.value); // 注意这里应该是finalMenu.value
  return finalMenu;
}